package cn.edu.cug.cs.gtl.gsm.item;

import cn.edu.cug.cs.gtl.common.Identifier;
import cn.edu.cug.cs.gtl.common.Identifiers;
import cn.edu.cug.cs.gtl.io.Storable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;

public class IndexItem implements Storable {
    int dataLength;
    Identifiers pageIdentifiers;

    public IndexItem(int dataLength, ArrayList<Identifier> pageIdentifiers) {
        this.dataLength = dataLength;
        this.pageIdentifiers = new Identifiers();
        for(Identifier i: pageIdentifiers){
            this.pageIdentifiers.add(i);
        }
    }


    public IndexItem() {
        this.dataLength = 0;
        this.pageIdentifiers = new Identifiers();
    }


    public int getDataLength() {
        return dataLength;
    }

    public void setDataLength(int dataLength) {
        this.dataLength = dataLength;
    }

    public ArrayList<Identifier> getPageIdentifiers() {
        return pageIdentifiers;
    }

    public Identifier getExternalPageIdentifier(){
        return pageIdentifiers.get(0);
    }

    public void addPageIdentifier(Identifier i){
        pageIdentifiers.add(i);
    }

    public void setPageIdentifiers(ArrayList<Identifier> pageIdentifiers) {
        this.pageIdentifiers.clear();
        for(Identifier i: pageIdentifiers){
            this.pageIdentifiers.add((Identifier) i.clone());
        }
    }

    public IndexItem(int dataLength, Identifier... pageIdentifiers) {
        this.dataLength = dataLength;
        this.pageIdentifiers = new Identifiers();
        for(Identifier i: pageIdentifiers){
            this.pageIdentifiers.add(i);
        }
    }

    @Override
    public Object clone() {
        Identifiers pageIdentifiers = new Identifiers();
        for(Identifier i : this.pageIdentifiers){
            pageIdentifiers.add((Identifier) i.clone());
        }
        IndexItem it = new IndexItem(this.dataLength,pageIdentifiers);
        return it;
    }

    @Override
    public boolean load(DataInput dataInput) throws IOException {
        dataLength = dataInput.readInt();
        pageIdentifiers.clear();
        pageIdentifiers.load(dataInput);
        return true;
    }

    @Override
    public boolean store(DataOutput dataOutput) throws IOException {
        //int dataLength;
        dataOutput.writeInt(dataLength);
        pageIdentifiers.store(dataOutput);
        return true;
    }
}
